﻿using CastingWellEquipmentGUI.Config;
using CastingWellEquipmentGUI.Dao;
using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.Utils;
using CastingWellEquipmentGUI.ViewModel.Common.Command;
using CastingWellEquipmentGUI.ViewModel.Common.WindowsManager;
using Confluent.Kafka;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using LiveCharts;
using LiveCharts.Wpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;

namespace CastingWellEquipmentGUI.ViewModel.Pages
{
    /// <summary>
    /// 润滑系统ViewModel
    /// </summary>
    public class LubricationSystemPageViewModel : ViewModelBase
    {
        #region 变量/常量
        /// <summary>
        /// 当前窗体名称
        /// </summary>
        private const string showPageTitle = "LubricationSystemPage";
        #endregion 变量/常量

        #region 页面属性
        /// <summary>
        /// 启动压力显示
        /// </summary>
        public string Lable_StartingPressure
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Lable_StartingPressure"); }
        }
        /// <summary>
        /// 停止压力显示
        /// </summary>
        public string Lable_StopingPressure
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Lable_StopingPressure"); }
        }
        /// <summary>
        /// PV显示
        /// </summary>
        public string Lable_PV
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Lable_PV"); }
        }
        private string _Button_PulsesNum;
        /// <summary>
        /// 脉冲数量设置
        /// </summary>
        public string Button_PulsesNum
        {
            get { return _Button_PulsesNum; }
            set
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_PulsesNum", value))
                {
                    _Button_PulsesNum = value;
                    RaisePropertyChanged("Button_PulsesNum");
                }
            }
        }
        private string _Button_StartTime;
        /// <summary>
        /// 启动时间设置
        /// </summary>
        public string Button_StartTime
        {
            get { return _Button_StartTime; }
            set
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_StartTime", value))
                {
                    _Button_StartTime = value;
                    RaisePropertyChanged("Button_StartTime");
                }
            }
        }
        private string _Button_StopTime;
        /// <summary>
        /// 停止时间设置
        /// </summary>
        public string Button_StopTime
        {
            get { return _Button_StopTime; }
            set
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_StopTime", value))
                {
                    _Button_StopTime = value;
                    RaisePropertyChanged("Button_StopTime");
                }
            }
        }
        private string _Button_CycleTime;
        /// <summary>
        /// 周期时间设置
        /// </summary>
        public string Button_CycleTime
        {
            get { return _Button_CycleTime; }
            set
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_CycleTime", value))
                {
                    _Button_CycleTime = value;
                    RaisePropertyChanged("Button_CycleTime");
                }
            }
        }
        private string _Button_AddOilImageUrl = "";
        /// <summary>
        /// 补油电磁阀按钮图片
        /// </summary>
        public string Button_AddOilImageUrl
        {
            get { return _Button_AddOilImageUrl; }
            set { _Button_AddOilImageUrl = value; RaisePropertyChanged("Button_AddOilImageUrl"); }
        }
        private string _Button_LeakOilImageUrl = "";
        /// <summary>
        /// 油滑电磁阀按钮图片
        /// </summary>
        public string Button_LeakOilImageUrl
        {
            get { return _Button_LeakOilImageUrl; }
            set { _Button_LeakOilImageUrl = value; RaisePropertyChanged("Button_LeakOilImageUrl"); }
        }

        #region 预检测项目
        private Visibility _PreDetectionVisibility;
        /// <summary>
        /// 预检测状态
        /// 注：控制预检测框显隐
        /// </summary>
        public Visibility PreDetectionVisibility
        {
            get { return _PreDetectionVisibility; }
            set { _PreDetectionVisibility = value; RaisePropertyChanged("PreDetectionVisibility"); }
        }
        /// <summary>
        /// 润滑油箱液位正常
        /// </summary>
        public Brush Label_PreCheck1
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_PreCheck1") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 脉冲润滑预检测正常
        /// </summary>
        public Brush Label_PreCheck2
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_PreCheck2") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        #endregion 预检测项目

        #endregion 页面属性

        #region 定义页面执行命令
        /// <summary>
        /// 数值设定按钮命令
        /// </summary>
        public DelegateCommand ShowModalPanelCommand { get; set; }
        /// <summary>
        /// 补油电磁阀
        /// </summary>
        public DelegateCommand AddOilCommand { get; set; }
        /// <summary>
        /// 油滑电磁阀
        /// </summary>
        public DelegateCommand LeakOilCommand { get; set; }
        #endregion 定义页面执行命令

        #region 线程对象
        /// <summary>
        /// 标签值变化监听线程
        /// </summary>
        private Thread tagInfoSyncThread = null;
        /// <summary>
        /// 趋势图生成
        /// </summary>
        private Thread readDataThread = null;
        #endregion 线程对象

        #region 方法
        /// <summary>
        /// 构造函数
        /// </summary>
        public LubricationSystemPageViewModel()
        {
            // 初始化命令
            initCommand();
            // 初始化线程
            initThread();
            // 消息通道注册
            initMessenger();
            // 初始化基础信息
            initBaseSet();
        }

        /// <summary>
        /// 初始化基础信息
        /// </summary>
        private void initBaseSet()
        {
            // 页面初始化
            HashSet<Control> tempHashSet = SysCommon.getCurrentControl(showPageTitle);
            if (tempHashSet.Count > 0)
            {
                DoChanged(tempHashSet);
            }
            /** 设定值初始化 **/
            _Button_PulsesNum = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Button_PulsesNum");
            RaisePropertyChanged("Button_PulsesNum");
            _Button_StartTime = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Button_StartTime");
            RaisePropertyChanged("Button_StartTime");

            _Button_StopTime = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Button_StopTime");
            RaisePropertyChanged("Button_StopTime");
            _Button_CycleTime = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Button_CycleTime");
            RaisePropertyChanged("Button_CycleTime");
        }

        /// <summary>
        /// 消息通道注册
        /// ViewModel之间数据通信使用，整个项目全局唯一
        /// </summary>
        private void initMessenger()
        {
            // 脉冲数量设置
            Messenger.Default.Register<string>(this, showPageTitle + "Button_PulsesNum", (message) =>
            {
                Button_PulsesNum = message.ToString();
            });
            // 启动时间设置
            Messenger.Default.Register<string>(this, showPageTitle + "Button_StartTime", (message) =>
            {
                Button_StartTime = message.ToString();
            });
            // 停止时间设置
            Messenger.Default.Register<string>(this, showPageTitle + "Button_StopTime", (message) =>
            {
                Button_StopTime = message.ToString();
            });
            // 周期时间设置
            Messenger.Default.Register<string>(this, showPageTitle + "Button_CycleTime", (message) =>
            {
                Button_CycleTime = message.ToString();
            });
            // 补油电磁阀开启或关闭
            Messenger.Default.Register<string>(this, showPageTitle + "Button_AddOil", (message) =>
            {
                setAddOilOnOrOff(message.ToString());
            });
            // 油滑电磁阀开启或关闭
            Messenger.Default.Register<string>(this, showPageTitle + "Button_LeakOil", (message) =>
            {
                setLeakOilOnOrOff(message.ToString());
            });
            //页面切换执行控件刷新
            Messenger.Default.Register<string>(this, showPageTitle + "_DoChange", (message) =>
            {
                HashSet<Control> tempHashSet = SysCommon.getCurrentControl(showPageTitle);
                if (tempHashSet.Count > 0)
                {
                    DoChanged(tempHashSet);
                }
            });
        }

        /// <summary>
        /// 设置补油电磁阀开启或关闭
        /// </summary>
        /// <param name="message">True Or False</param>
        private void setAddOilOnOrOff(string message)
        {
            if (message == "" || message == null)
            {
                return;
            }
            if (message == "True")
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_AddOil_Open", "true"))
                {
                    Button_AddOilImageUrl = "/images/LubricationSystem/Open.png";
                }
            }
            else if (message == "False")
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_AddOil_Close", "true"))
                {
                    Button_AddOilImageUrl = "/images/LubricationSystem/Close.png";
                }
            }
        }

        /// <summary>
        /// 设置油滑电磁阀开启或关闭
        /// </summary>
        /// <param name="message"></param>
        private void setLeakOilOnOrOff(string message)
        {
            if (message == "" || message == null)
            {
                return;
            }
            if (message == "True")
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_LeakOil_Open", "true"))
                {
                    Button_LeakOilImageUrl = "/images/LubricationSystem/Open.png";
                }
            }
            else if (message == "False")
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_LeakOil_Close", "true"))
                {
                    Button_LeakOilImageUrl = "/images/LubricationSystem/Close.png";
                }
            }
        }
        /// <summary>
        /// 初始化线程
        /// </summary>
        private void initThread()
        {
            // 标签值变化监听线程
            tagInfoSyncThread = new Thread(syncThreadFunc);
            tagInfoSyncThread.IsBackground = true;
            tagInfoSyncThread.Start();
            // 趋势图
            //readDataThread = new Thread(ReadDataForRedis);
            ////readDataThread.SetApartmentState(ApartmentState.STA);
            //readDataThread.IsBackground = true;
            //readDataThread.Start();
        }

        /// <summary>
        /// 标签值变化监听
        /// </summary>
        private void syncThreadFunc()
        {
            // 创建消费者对象
            IConsumer<string, object> KafkaConsumer = KafkaHelper.GetConsumer();
            while (true)
            {
                if (SystemConfig.systemState == "预检测" || SystemConfig.systemState == "可见许可")
                {
                    PreDetectionVisibility = Visibility.Visible;
                }
                else
                {
                    PreDetectionVisibility = Visibility.Hidden;
                }
                // 网络中断不进行消费监听
                if (SystemConfig.SystemStatus == "网络中断")
                {
                    Thread.Sleep(1000);
                    continue;
                }
                if (ThreadController.RoundBarLubricationSystemThreadState)
                {
                    //开始消费
                    var result = KafkaConsumer.Consume();
                    if (result != null)
                    {
                        //手动提交
                        KafkaConsumer.Commit(result);
                        //获取消息内容
                        string tagId = result.Message.Value.ToString();
                        HashSet<Control> hashSet = KafkaHelper.UpdateCurrentUserTagValue(Int32.Parse(tagId), KafkaHelper.GetTagValueByKey(tagId.ToString()), showPageTitle);
                        if (hashSet != null)
                        {
                            DoChanged(hashSet);
                        }
                    }
                }
                Thread.Sleep(10);
            }
        }

        /// <summary>
        /// 执行动作
        /// </summary>
        /// <param name="hashSet"></param>
        private void DoChanged(HashSet<Control> hashSet)
        {
            //遍历返回的控件信息刷新对应的控件
            foreach (Control item in hashSet)
            {
                switch (item.ControlName)
                {
                    /** 补油电磁阀开启 **/
                    case "Button_AddOil_Open":
                        if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "true")
                        {
                            Button_AddOilImageUrl = "/images/LubricationSystem/Open.png";
                        }
                        break;
                    /** 补油电磁阀关闭 **/
                    case "Button_AddOil_Close":
                        if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "true")
                        {
                            Button_AddOilImageUrl = "/images/LubricationSystem/Close.png";
                        }
                        break;
                    /** 油滑电磁阀开启 **/
                    case "Button_LeakOil_Open":
                        if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "true")
                        {
                            Button_LeakOilImageUrl = "/images/LubricationSystem/Open.png";
                        }
                        break;
                    /** 油滑电磁阀关闭 **/
                    case "Button_LeakOil_Close":
                        if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "true")
                        {
                            Button_LeakOilImageUrl = "/images/LubricationSystem/Close.png";
                        }
                        break;
                    default:
                        /** 刷新页面值变化信息 **/
                        RaisePropertyChanged(item.ControlName);
                        break;
                }
            }
        }

        /// <summary>
        /// 初始化命令
        /// </summary>
        private void initCommand()
        {
            // 数值设定按钮命令
            ShowModalPanelCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(showModalPanelHandler)
            };
            // 补油电磁阀
            AddOilCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(oilCommandHandler)
            };
            // 补油电磁阀
            LeakOilCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(oilCommandHandler)
            };
        }

        /// <summary>
        /// 补油或油滑电磁阀按钮触发
        /// </summary>
        /// <param name="obj"></param>
        private void oilCommandHandler(object obj)
        {
            // 获取参数，此处参数为按钮名称
            string param = obj.ToString();
            WindowManager.ShowModalOnOrOffPanel("OnOrOffPanel", showPageTitle + param);
        }

        /// <summary>
        /// 数值设定按钮命令
        /// </summary>
        /// <param name="obj"></param>
        private void showModalPanelHandler(object obj)
        {
            string param = obj.ToString();
            switch (param)
            {
                // 脉冲数量设置
                case "Button_PulsesNum":
                    WindowManager.ShowModalDigitalInputPanel("SetCVPanel", showPageTitle + "Button_PulsesNum", Button_PulsesNum);
                    break;
                // 启动时间设置
                case "Button_StartTime":
                    WindowManager.ShowModalDigitalInputPanel("SetCVPanel", showPageTitle + "Button_StartTime", Button_StartTime);
                    break;
                // 停止时间设置
                case "Button_StopTime":
                    WindowManager.ShowModalDigitalInputPanel("SetCVPanel", showPageTitle + "Button_StopTime", Button_StopTime);
                    break;
                // 周期时间设置
                case "Button_CycleTime":
                    WindowManager.ShowModalDigitalInputPanel("SetCVPanel", showPageTitle + "Button_CycleTime", Button_CycleTime);
                    break;
                default:
                    break;
            }
        }

        #region 趋势图相关
        private ObservableCollection<LineSeries> _Series;
        public ObservableCollection<LineSeries> Series
        {

            get { return _Series; }
            set
            {
                _Series = value;
                RaisePropertyChanged(() => Series);
            }
        }

        private List<string> _Labels;
        public List<string> Labels
        {
            get { return _Labels; }
            set
            {
                _Labels = value;
                RaisePropertyChanged(() => Labels);
            }
        }
        private void ReadDataForRedis()
        {

            Series = new ObservableCollection<LineSeries>();
            DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
            dateTimeFormatInfo.LongDatePattern = "yyyy年MM月dd日 HH时mm分ss秒";
            DateTime startDateTime = Convert.ToDateTime(getDateTimeNow(), dateTimeFormatInfo);
            DateTime currentDateTime = startDateTime.AddSeconds(-1);
            string MessageQueueKey = currentDateTime.ToString("yyyy年MM月dd日 HH时mm分ss秒");
            // 获取趋势数据
            List<RedisTrend> obj = RedisHelper.GetStringList<List<RedisTrend>>(MessageQueueKey);
            // 描绘线条数量
            for (int i = 0; i < obj.Count; i++)
            {
                Application.Current.Dispatcher.Invoke(new Action(delegate
                {
                    LineSeries series = new LineSeries
                    {
                        Title = obj[i].TagName,
                        Values = new ChartValues<double>()
                    };
                    Series.Add(series);
                }));
            }

            Labels = new List<string>();
            while (true)
            {
                Application.Current.Dispatcher.Invoke(new Action(delegate
                {
                    MessageQueueKey = currentDateTime.ToString("yyyy年MM月dd日 HH时mm分ss秒");
                    Labels.Add(Convert.ToDateTime(MessageQueueKey, dateTimeFormatInfo).ToString("HH:mm:ss"));
                    if (Labels.Count > 5)
                    {
                        Labels.RemoveAt(0);
                    }
                    // 获取趋势数据
                    List<RedisTrend> redisTrends = RedisHelper.GetStringList<List<RedisTrend>>(MessageQueueKey);
                    if (redisTrends != null && redisTrends.Count > 0)
                    {
                        for (int i = 0; i < redisTrends.Count; i++)
                        {
                            for (int j = 0; j < Series.Count; j++)
                            {
                                if (Series[j].Title == redisTrends[i].TagName)
                                {
                                    Series[j].Values.Add(Convert.ToDouble(redisTrends[i].Value));
                                    if (Series[j].Values.Count > 5)
                                    {
                                        Series[j].Values.RemoveAt(0);
                                    }
                                }
                            }
                        }
                    }
                }));
                Thread.Sleep(1000);
                // 减1秒原因：避免网关没有及时生成当前时间的数据到Redis中而发生的异常
                currentDateTime = Convert.ToDateTime(getDateTimeNow(), dateTimeFormatInfo).AddSeconds(-1);
            }
        }

        /// <summary>
        /// 获取当期服务器时间
        /// </summary>
        /// <returns></returns>
        private string getDateTimeNow()
        {
            ObservableCollection<String> dateNow = DapperToolsThisSystem.QueryOc<String>("select GETDATE() as DateTime");
            return dateNow.Last();
        }
        #endregion 趋势图相关

        #endregion 方法
    }
}
